package apis

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	config2 "github.com/go-admin-team/go-admin-core/config"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/config"
	"github.com/google/uuid"
	"net/http"
	"strconv"
	"time"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/pkg/util"
	"tuowei.com/pkg/xlog"
)

type ApiLogin struct {
	api.Api
	Base
}

func (e ApiLogin) Logout(ctx *gin.Context) {
	err := e.MakeContext(ctx).MakeOrm().Errors
	if err != nil {
		e.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	err, studentId := e.GetUser(&e.Api)
	if err != nil {
		e.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	// 直接更新login状态
	err = e.Orm.Table(models.SysStudent{}.TableName()).Where("id = ?", studentId).Update("logined", 0).Error
	if err != nil {
		e.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	e.OK(nil, "退出成功")
}

func (e ApiLogin) CodeLogin(c *gin.Context) {
	req := dto.CodeLoginReq{}
	s := service.ApiStudent{}
	err := e.MakeContext(c).MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 固定一个账号，用来用于上架审核,此账号随便输入验证码都可以
	appTel := config2.Get("ACCOUNT_FOR_APP").Int(0)
	if strconv.Itoa(appTel) != req.Phone {
		code, err := config.GetRedisClient().Get(util.MakeMessageCodeKey("student", req.Phone)).Result()
		if err != nil {
			xlog.Error(err)
			e.Error(500, err, "请先获取验证码")
			return
		}

		if req.Code != code {
			err = errors.New("短信验证码错误")
			e.Error(500, err, err.Error())
			return
		}
	}

	var student models.SysStudent
	err = s.GetUserInfoByPhone(&student, req.Phone)
	if err != nil {
		studentData := &dto.SysStudentInsertReq{
			SerialNum: "TW-STUDENT-" + time.Now().Format("20060102150405"),
			Phone:     req.Phone,
			Status:    1,
		}
		lastID, insertErr := s.Insert(studentData)
		if insertErr != nil {
			xlog.Error(insertErr)
			e.Error(500, insertErr, insertErr.Error())
			return
		}
		student.Id = lastID
		student.Phone = req.Phone
	} else {
		if student.Status == 0 {
			err = errors.New("您已被管理员禁用，请联系管理员")
			e.Error(500, err, err.Error())
			return
		}

	}
	// 检测学员购买状态
	// 结业状态不让登陆
	if student.BuyStatus == 3 {
		e.Error(http.StatusInternalServerError, nil, err.Error())
		return
	}
	// 更新学生为登陆状态
	uid := uuid.NewString()
	e.Orm.Table(models.SysStudent{}.TableName()).Where("id = ?", student.Id).Update("logined", uid)
	student.Logined = uid
	claim := StudentClaims{
		Student:        &student,
		StandardClaims: jwt.StandardClaims{},
	}
	now := time.Now()
	claim.StandardClaims.IssuedAt = now.Unix()
	claim.StandardClaims.ExpiresAt = now.Add(time.Duration(config.JwtConfig.Timeout) * time.Second).Unix()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenStr, err := token.SignedString([]byte(config.JwtConfig.Secret))
	if err != nil {
		xlog.Error(http.StatusInternalServerError, err, err.Error())
		return
	}

	e.Context.JSON(http.StatusOK, gin.H{
		"code":          http.StatusOK,
		"is_registered": student.IsRegistered,
		"expire":        now.Add(time.Duration(config.JwtConfig.Timeout) * time.Second),
		"token":         tokenStr,
	})
	return

}
